import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Avatar,
  Upload,
  message,
  Row,
  Col,
  Tabs,
  List,
  Tag,
  Space,
  Modal,
  Timeline,
  Badge,
  Descriptions,
  Statistic,
  Progress,
  Alert
} from 'antd';
import {
  UserOutlined,
  CameraOutlined,
  LockOutlined,
  MailOutlined,
  PhoneOutlined,
  SafetyOutlined,
  BellOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  DashboardOutlined,
  ReloadOutlined,
  EditOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { useAdminAuth } from '../../hooks/useAuth';
import { adminUserAPI } from '../../services/api';
import { encryptPassword } from '../../utils/auth';

const { TabPane } = Tabs;

const AdminProfile = () => {
  const { user, updateUser } = useAdminAuth();
  const [loading, setLoading] = useState(false);
  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [activeTab, setActiveTab] = useState('profile');
  const [loginLogs, setLoginLogs] = useState([]);
  const [operationStats, setOperationStats] = useState({
    today: 0,
    week: 0,
    month: 0,
    total: 0
  });
  const [notifications, setNotifications] = useState([
    { id: 1, title: '系统通知', content: '系统将于今晚12点进行维护', time: '2小时前', read: false, type: 'info' },
    { id: 2, title: '安全提醒', content: '您的密码已经90天未修改', time: '1天前', read: false, type: 'warning' },
    { id: 3, title: '操作成功', content: '个人信息更新成功', time: '3天前', read: true, type: 'success' }
  ]);

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  const primaryButtonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '500',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadUserData();
    loadLoginLogs();
    loadOperationStats();
  }, []);

  const loadUserData = () => {
    if (user) {
      profileForm.setFieldsValue({
        username: user.username,
        nickname: user.nickname,
        email: user.email,
        phone: user.phone
      });
    }
  };

  const loadLoginLogs = async () => {
    try {
      const response = await adminUserAPI.getLoginLogs(user?.id);
      if (response.success) {
        setLoginLogs(response.data);
      }
    } catch (error) {
      console.error('加载登录日志失败:', error);
    }
  };

  const loadOperationStats = async () => {
    try {
      const response = await adminUserAPI.getOperationStats(user?.id);
      if (response.success) {
        setOperationStats(response.data);
      }
    } catch (error) {
      console.error('加载操作统计失败:', error);
    }
  };

  const handleProfileSubmit = async () => {
    try {
      const values = await profileForm.validateFields();
      setLoading(true);
      
      const response = await adminUserAPI.updateProfile(user.id, values);
      if (response.success) {
        message.success('个人信息更新成功');
        updateUser({ ...user, ...values });
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async () => {
    try {
      const values = await passwordForm.validateFields();
      
      // 验证原密码
      const encryptedOldPassword = encryptPassword(values.oldPassword);
      // 这里应该调用API验证原密码
      
      const encryptedNewPassword = encryptPassword(values.newPassword);
      
      setLoading(true);
      const response = await adminUserAPI.changePassword(user.id, {
        oldPassword: encryptedOldPassword,
        newPassword: encryptedNewPassword
      });
      
      if (response.success) {
        message.success('密码修改成功，请重新登录');
        passwordForm.resetFields();
        // 这里应该跳转到登录页
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('密码修改失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAvatarUpload = async (info) => {
    if (info.file.status === 'done') {
      // 这里应该处理头像上传
      message.success('头像上传成功');
    }
  };

  const markNotificationAsRead = (id) => {
    setNotifications(prev => 
      prev.map(item => 
        item.id === id ? { ...item, read: true } : item
      )
    );
  };

  const markAllAsRead = () => {
    setNotifications(prev => 
      prev.map(item => ({ ...item, read: true }))
    );
  };

  const getNotificationIcon = (type) => {
    const iconMap = {
      'info': <BellOutlined style={{ color: '#1890ff' }} />,
      'warning': <ClockCircleOutlined style={{ color: '#faad14' }} />,
      'success': <CheckCircleOutlined style={{ color: '#52c41a' }} />,
      'error': <ClockCircleOutlined style={{ color: '#f5222d' }} />
    };
    return iconMap[type] || <BellOutlined />;
  };

  return (
    <div>
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="基本信息" key="profile">
            <Row gutter={24}>
              <Col span={16}>
                <Form
                  form={profileForm}
                  layout="vertical"
                  onFinish={handleProfileSubmit}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="username"
                        label="用户名"
                      >
                        <Input 
                          disabled 
                          prefix={<UserOutlined />}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="nickname"
                        label="昵称"
                        rules={[{ required: true, message: '请输入昵称' }]}
                      >
                        <Input placeholder="请输入昵称" />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="email"
                        label="邮箱"
                        rules={[
                          { type: 'email', message: '请输入有效的邮箱地址' }
                        ]}
                      >
                        <Input 
                          placeholder="请输入邮箱" 
                          prefix={<MailOutlined />}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="phone"
                        label="手机号"
                        rules={[
                          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                        ]}
                      >
                        <Input 
                          placeholder="请输入手机号" 
                          prefix={<PhoneOutlined />}
                        />
                      </Form.Item>
                    </Col>
                  </Row>

                  <Form.Item>
                    <Space>
                      <Button 
                        type="primary" 
                        htmlType="submit" 
                        loading={loading}
                        icon={<SaveOutlined />}
                        style={primaryButtonStyle}
                      >
                        保存修改
                      </Button>
                      <Button 
                        onClick={() => profileForm.resetFields()}
                        style={buttonStyle}
                      >
                        重置
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              </Col>

              <Col span={8}>
                <Card
                  title="个人头像"
                  bordered={false}
                  bodyStyle={{ textAlign: 'center' }}
                  extra={
                    <Button 
                      type="link" 
                      icon={<EditOutlined />} 
                      size="small"
                      style={buttonStyle}
                    >
                      编辑
                    </Button>
                  }
                >
                  <Upload
                    showUploadList={false}
                    beforeUpload={() => false}
                    onChange={handleAvatarUpload}
                  >
                    <div style={{ position: 'relative', display: 'inline-block' }}>
                      <Avatar
                        size={120}
                        icon={<UserOutlined />}
                        src={user?.avatar}
                        style={{ backgroundColor: '#1890ff' }}
                      />
                      <Button
                        icon={<CameraOutlined />}
                        shape="circle"
                        size="small"
                        style={{
                          position: 'absolute',
                          bottom: 0,
                          right: 0,
                          backgroundColor: '#fff',
                          borderColor: '#d9d9d9'
                        }}
                      />
                    </div>
                  </Upload>
                  <div style={{ marginTop: 16 }}>
                    <h3>{user?.nickname || user?.username}</h3>
                    <Space wrap style={{ marginTop: 8 }}>
                      {user?.roles?.map(role => (
                        <Tag key={role.id} color="blue">{role.name}</Tag>
                      ))}
                    </Space>
                  </div>
                </Card>

                <Card
                  title="账户信息"
                  bordered={false}
                  style={{ marginTop: 16 }}
                >
                  <Descriptions column={1} size="small">
                    <Descriptions.Item label="账户状态">
                      <Badge status="success" text="正常" />
                    </Descriptions.Item>
                    <Descriptions.Item label="注册时间">
                      {user?.createTime ? new Date(user.createTime).toLocaleDateString() : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="最后登录">
                      {user?.lastLoginTime ? new Date(user.lastLoginTime).toLocaleString() : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="登录IP">
                      {user?.lastLoginIp || '-'}
                    </Descriptions.Item>
                  </Descriptions>
                </Card>
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="修改密码" key="password">
            <Row justify="center">
              <Col span={12}>
                <Alert
                  message="密码安全提示"
                  description="为了保障账户安全，建议您定期修改密码，并使用强密码（包含大小写字母、数字和特殊字符）。"
                  type="info"
                  showIcon
                  style={{ marginBottom: 24 }}
                />
                
                <Form
                  form={passwordForm}
                  layout="vertical"
                  onFinish={handlePasswordSubmit}
                >
                  <Form.Item
                    name="oldPassword"
                    label="原密码"
                    rules={[{ required: true, message: '请输入原密码' }]}
                  >
                    <Input.Password 
                      placeholder="请输入原密码"
                      prefix={<LockOutlined />}
                    />
                  </Form.Item>

                  <Form.Item
                    name="newPassword"
                    label="新密码"
                    rules={[
                      { required: true, message: '请输入新密码' },
                      { min: 6, message: '密码至少6位' },
                      { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/, 
                        message: '密码必须包含大小写字母和数字' }
                    ]}
                  >
                    <Input.Password 
                      placeholder="请输入新密码"
                      prefix={<LockOutlined />}
                    />
                  </Form.Item>

                  <Form.Item
                    name="confirmPassword"
                    label="确认密码"
                    dependencies={['newPassword']}
                    rules={[
                      { required: true, message: '请确认新密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('newPassword') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                  >
                    <Input.Password 
                      placeholder="请再次输入新密码"
                      prefix={<LockOutlined />}
                    />
                  </Form.Item>

                  <Form.Item>
                    <Space>
                      <Button 
                        type="primary" 
                        htmlType="submit" 
                        loading={loading}
                        icon={<SafetyOutlined />}
                        style={primaryButtonStyle}
                      >
                        修改密码
                      </Button>
                      <Button 
                        onClick={() => passwordForm.resetFields()}
                        style={buttonStyle}
                      >
                        重置
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              </Col>
            </Row>
          </TabPane>

          <TabPane tab="操作统计" key="statistics">
            <div style={{ marginBottom: 16 }}>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={loadOperationStats}
                style={buttonStyle}
              >
                刷新数据
              </Button>
            </div>
            
            <Row gutter={[16, 16]}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="今日操作"
                    value={operationStats.today}
                    prefix={<DashboardOutlined />}
                    valueStyle={{ color: '#3f8600' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="本周操作"
                    value={operationStats.week}
                    prefix={<DashboardOutlined />}
                    valueStyle={{ color: '#1890ff' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="本月操作"
                    value={operationStats.month}
                    prefix={<DashboardOutlined />}
                    valueStyle={{ color: '#cf1322' }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="总操作数"
                    value={operationStats.total}
                    prefix={<DashboardOutlined />}
                  />
                </Card>
              </Col>
            </Row>

            <Card title="操作分布" style={{ marginTop: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <Progress
                      type="circle"
                      percent={75}
                      format={() => '商品管理'}
                      strokeColor="#52c41a"
                    />
                    <p style={{ marginTop: 16 }}>325次操作</p>
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <Progress
                      type="circle"
                      percent={60}
                      format={() => '订单管理'}
                      strokeColor="#1890ff"
                    />
                    <p style={{ marginTop: 16 }}>260次操作</p>
                  </div>
                </Col>
                <Col span={8}>
                  <div style={{ textAlign: 'center' }}>
                    <Progress
                      type="circle"
                      percent={45}
                      format={() => '用户管理'}
                      strokeColor="#faad14"
                    />
                    <p style={{ marginTop: 16 }}>195次操作</p>
                  </div>
                </Col>
              </Row>
            </Card>

            <Card title="最近登录记录" style={{ marginTop: 16 }}>
              <Timeline>
                {loginLogs.map(log => (
                  <Timeline.Item 
                    key={log.id}
                    color={log.success ? 'green' : 'red'}
                  >
                    <p>
                      {new Date(log.time).toLocaleString()} - 
                      {log.success ? '登录成功' : '登录失败'}
                    </p>
                    <p style={{ fontSize: '12px', color: '#999' }}>
                      IP: {log.ip} | 地点: {log.location || '未知'} | 
                      设备: {log.device || '未知设备'}
                    </p>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </TabPane>

          <TabPane tab="消息通知" key="notifications">
            <Card
              title="系统通知"
              extra={
                <Space>
                  <Button 
                    type="link" 
                    onClick={markAllAsRead}
                    style={buttonStyle}
                  >
                    全部标记为已读
                  </Button>
                  <Button 
                    icon={<ReloadOutlined />}
                    style={buttonStyle}
                  >
                    刷新
                  </Button>
                </Space>
              }
            >
              <List
                itemLayout="horizontal"
                dataSource={notifications}
                renderItem={item => (
                  <List.Item
                    actions={[
                      !item.read && (
                        <Button 
                          type="link" 
                          size="small"
                          onClick={() => markNotificationAsRead(item.id)}
                          style={buttonStyle}
                        >
                          标记已读
                        </Button>
                      )
                    ]}
                  >
                    <List.Item.Meta
                      avatar={getNotificationIcon(item.type)}
                      title={
                        <Space>
                          <span style={{ fontWeight: item.read ? 'normal' : 'bold' }}>
                            {item.title}
                          </span>
                          {!item.read && <Badge status="processing" />}
                        </Space>
                      }
                      description={
                        <div>
                          <div>{item.content}</div>
                          <div style={{ fontSize: '12px', color: '#999', marginTop: 4 }}>
                            {item.time}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default AdminProfile;